package servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import dataDAOImpl.MySQLCommodityBatchDAO;
import dataDAOImpl.MySQLProductBatchDAO;
import dataDAOInterfaces.DALException;
import dataDAOInterfaces.ICommodityBatchDAO;
import dataDAOInterfaces.IProductBatchDAO;
import dataDTO.CommodityBatchDTO;
import dataDTO.ProductBatchDTO;
import service.DataService;
import service.ErrorService;
import service.ValidateCommodityBatch;
import service.ValidateProductBatch;


/**
 * Servlet implementation class Vaerft
 */
public class Vaerft extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private ValidateProductBatch validateProductBatch = new ValidateProductBatch();
	private ValidateCommodityBatch validateCommodityBatch = new ValidateCommodityBatch();

	private ProductBatchDTO productBatchDTO;
	private IProductBatchDAO productBatchDAO = new MySQLProductBatchDAO();

	private CommodityBatchDTO commodityBatchDTO;
	private ICommodityBatchDAO commodityBatchDAO = new MySQLCommodityBatchDAO();

	private DataService data = new DataService();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Vaerft() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String page = request.getParameter("page");
		RequestDispatcher dispatcher;

		if (isLoggedIn(request))
		{
			try
			{
				if (page.equals("1"))
				{
					dispatcher = request.getRequestDispatcher("/WEB-INF/vaerft/Default.jsp");
					dispatcher.forward(request, response);
				}
				else if (page.equals("2"))
				{	
					if(!request.getMethod().equals("POST"))
					{
						dispatcher = request.getRequestDispatcher("/WEB-INF/vaerft/CreateProductBatch.jsp");
						dispatcher.forward(request, response);
					}
					else
					{
						String pbId = request.getParameter("pbId");
						String status = request.getParameter("status");
						String[] recipeId = request.getParameter("recipeName").split(" ");
						createProductBatch(pbId, recipeId[0], status, request, response);
					}
				}
				else if (page.equals("3"))
				{
					if(!request.getMethod().equals("POST"))
					{
						this.setProductBeanData(request, response);
						request.setAttribute("DataService", data);
						dispatcher = request.getRequestDispatcher("/WEB-INF/vaerft/EditProductBatch.jsp");
						dispatcher.forward(request, response);
					}else
					{
						String pbId = request.getParameter("id");
						String recipeId = request.getParameter("recipeId");
						String status = request.getParameter("status");
						data.setPbId(request.getParameter("id"));
						request.setAttribute("DataService", data);
						changeProductBatch(pbId, recipeId, status, request, response);
					}
				}
				else if (page.equals("4"))
				{
					dispatcher = request.getRequestDispatcher("/WEB-INF/vaerft/ShowCommodityBatch.jsp");
					dispatcher.forward(request, response);
				}
				else if(page.equals("5")){ 
					if(!request.getMethod().equals("POST"))
					{
						dispatcher = request.getRequestDispatcher("/WEB-INF/vaerft/CreateCommodityBatch.jsp");
						dispatcher.forward(request, response);
					}else
					{
						String cbId = request.getParameter("rbId");
						String volume = request.getParameter("volume");
						String[] commodityId = request.getParameter("commodityName").split(" ");
						createCommodityBatch(cbId, commodityId[0], volume, request, response);
					}
				}
				else if(page.equals("6")){ 
					if(!request.getMethod().equals("POST"))
					{
						this.setCommodityBeanData(request, response);
						request.setAttribute("DataService", data);
						dispatcher = request.getRequestDispatcher("/WEB-INF/vaerft/EditCommodityBatch.jsp");
						dispatcher.forward(request, response);
					}else
					{
						data.setRbId(request.getParameter("id"));
						request.setAttribute("DataService", data);
						String cbId = request.getParameter("id");
						String commodityId = request.getParameter("commodityNr");
						String volume = request.getParameter("volume");
						System.out.println(cbId+"  "+commodityId+"  "+volume);
						changeCommodityBatch(cbId, commodityId, volume, request, response);
					}
				}
				else if(page.equals("7"))
				{
					String id = request.getParameter("id");
					data.setPbId(id);
					request.setAttribute("DataService", data);	//Sender objektet med requestet
					dispatcher = request.getRequestDispatcher("/WEB-INF/vaerft/ProductBatchComp.jsp");
					dispatcher.forward(request, response);
				}
				else if (page.equals("8"))
				{
					String id = request.getParameter("id");
					data.setRbId("id");
					request.setAttribute("DataService", data);	//Sender objektet med requestet
					dispatcher = request.getRequestDispatcher("/WEB-INF/vaerft/CommodityCompBatch.jsp");
					dispatcher.forward(request, response);
				}
				else
				{
					dispatcher = request.getRequestDispatcher("/WEB-INF/vaerft/Default.jsp");
					dispatcher.forward(request, response);
				}
			}
			catch (NullPointerException e)
			{
				//Der kastes NullPointerException hvis man ikke angiver page attributten i URLen
				//Derfor forwardes til default
				dispatcher = request.getRequestDispatcher("/WEB-INF/vaerft/Default.jsp");
				dispatcher.forward(request, response);
				System.out.println("Fejl: "+e);
			}
		}
		else
		{
			dispatcher = request.getRequestDispatcher("/Afvejningssystem"); 
			dispatcher.forward(request, response);
		}
	}
	
//	################## HJÆLPE METODER ################################

	private boolean isLoggedIn(HttpServletRequest request)
	{
		HttpSession session = request.getSession();
		return Integer.parseInt(session.getAttribute("user").toString()) <= 3;	//Her får både rolle 1, 2 og 3 adgang (admin, farmaceut og værkfører)
	}

	private void createProductBatch(String pbId, String recipeId, String status, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		RequestDispatcher dispatcher;		
		validateProductBatch.validate(pbId, recipeId, status);
		ErrorService error = validateProductBatch.createError();
		error.setError(validateProductBatch.getError());
		request.setAttribute("error", error);

		if(error.getError().isEmpty())
		{
			productBatchDTO = new ProductBatchDTO(Integer.parseInt(pbId), Integer.parseInt(status), Integer.parseInt(recipeId));
			try {
				productBatchDAO.createProductBatch(productBatchDTO);
				dispatcher = request.getRequestDispatcher("/WEB-INF/vaerft/Default.jsp");
				dispatcher.forward(request, response);
			} catch (DALException e) {
				System.out.println(e.getLocalizedMessage());
				error.setError("ID er i brug");
				request.setAttribute("error", error);
				dispatcher = request.getRequestDispatcher("/WEB-INF/vaerft/CreateProductBatch.jsp");
				dispatcher.forward(request, response);
			}
		}
		else
		{
			dispatcher = request.getRequestDispatcher("/WEB-INF/vaerft/CreateProductBatch.jsp");
			dispatcher.forward(request, response);
		}
	}

	private void changeProductBatch(String pbId, String recipeId, String status, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		RequestDispatcher dispatcher;		
		validateProductBatch.validate(pbId, recipeId, status);
		ErrorService error = validateProductBatch.createError();
		error.setError(validateProductBatch.getError());
		request.setAttribute("error", error);

		if(error.getError().isEmpty()){
			productBatchDTO = new ProductBatchDTO(Integer.parseInt(pbId), Integer.parseInt(status), Integer.parseInt(recipeId));
			try {
				productBatchDAO.updateProductBatch(productBatchDTO);
				dispatcher = request.getRequestDispatcher("/WEB-INF/vaerft/Default.jsp");
				dispatcher.forward(request, response);
			} catch (DALException e) {
				System.out.println(e.getLocalizedMessage());
				error.setError(e.getLocalizedMessage());
				request.setAttribute("error", error);
				dispatcher = request.getRequestDispatcher("/WEB-INF/vaerft/EditProductBatch.jsp");
				dispatcher.forward(request, response);
			}
		}
		else
		{
			dispatcher = request.getRequestDispatcher("/WEB-INF/vaerft/EditProductBatch.jsp");
			dispatcher.forward(request, response);
		}

	}

	private void createCommodityBatch(String rbId, String commodityId, String volume, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		RequestDispatcher dispatcher;		
		validateCommodityBatch.validate(rbId, commodityId, volume);
		ErrorService error = validateCommodityBatch.createError();
		error.setError(validateCommodityBatch.getError());
		request.setAttribute("error", error);

		if(error.getError().isEmpty())
		{
			commodityBatchDTO = new CommodityBatchDTO(Integer.parseInt(rbId), Integer.parseInt(commodityId), Integer.parseInt(volume));
			try {
				commodityBatchDAO.createCommodityBatch(commodityBatchDTO);
				dispatcher = request.getRequestDispatcher("/WEB-INF/vaerft/ShowCommodityBatch.jsp");
				dispatcher.forward(request, response);
			} catch (DALException e) {
				System.out.println(e.getLocalizedMessage());
				error.setError("ID er i brug");
				request.setAttribute("error", error);
				dispatcher = request.getRequestDispatcher("/WEB-INF/vaerft/CreateCommodityBatch.jsp");
				dispatcher.forward(request, response);
			}
		}
		else
		{
			dispatcher = request.getRequestDispatcher("/WEB-INF/vaerft/CreateCommodityBatch.jsp");
			dispatcher.forward(request, response);
		}
	}

	private void changeCommodityBatch(String cbId, String commodityId, String volume, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		RequestDispatcher dispatcher;	
		validateCommodityBatch.validate(cbId, commodityId, volume);
		ErrorService error = validateCommodityBatch.createError();
		error.setError(validateCommodityBatch.getError());
		request.setAttribute("error", error);

		if(error.getError().isEmpty()){
			commodityBatchDTO = new CommodityBatchDTO(Integer.parseInt(cbId), Integer.parseInt(commodityId), Double.parseDouble(volume));
			try {
				commodityBatchDAO.updateCommodityBatch(commodityBatchDTO);
				dispatcher = request.getRequestDispatcher("/WEB-INF/vaerft/ShowCommodityBatch.jsp");
				dispatcher.forward(request, response);
			} catch (DALException e) {
				System.out.println(e.getLocalizedMessage());
				error.setError(e.getLocalizedMessage());
				request.setAttribute("error", error);
				dispatcher = request.getRequestDispatcher("/WEB-INF/vaerft/EditCommodityBatch.jsp");
				dispatcher.forward(request, response);
			}
		}
		else
		{
			dispatcher = request.getRequestDispatcher("/WEB-INF/vaerft/EditCommodityBatch.jsp");
			dispatcher.forward(request, response);
		}

	}
	
	private void setProductBeanData(HttpServletRequest request, HttpServletResponse response)
	{	
		String id = request.getParameter("id");
		try 
		{
			productBatchDTO = productBatchDAO.getProductBatch(Integer.parseInt(id));
			data.setPbId(Integer.toString(productBatchDTO.getPbId()));
			data.setRecipeId(Integer.toString(productBatchDTO.getRecipeId()));
			data.setStatus(Integer.toString(productBatchDTO.getStatus()));
		} 
		catch (DALException e)
		{
			System.out.println("DAL Fejl: "+e);
		}
		catch (Exception e)
		{
			System.out.println("Fejl: "+e);
		}
	}
	
	private void setCommodityBeanData(HttpServletRequest request, HttpServletResponse response)
	{	
		String id = request.getParameter("id");
		try 
		{
			commodityBatchDTO = commodityBatchDAO.getCommodityBatch(Integer.parseInt(id));
			data.setRbId(Integer.toString(commodityBatchDTO.getCbId()));
			data.setCommodityNr(Integer.toString(commodityBatchDTO.getCommodityId()));
			data.setVolume(Double.toString(commodityBatchDTO.getVolume()));
		} 
		catch (DALException e)
		{
			System.out.println("DAL Fejl: "+e);
		}
		catch (Exception e)
		{
			System.out.println("Fejl: "+e);
		}
	}

}
